package com.tongtailian.www.stir.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tongtailian.www.stir.R;
import com.tongtailian.www.stir.adapter.ConfigAdapter;
import com.tongtailian.www.stir.adapter.SelectGroupAdapter;
import com.tongtailian.www.stir.base.BaseActivity;
import com.tongtailian.www.stir.bean.ConfigBean;
import com.tongtailian.www.stir.bean.DeviceStateFram;
import com.tongtailian.www.stir.bean.NumberBean;
import com.tongtailian.www.stir.bleinterface.MyBleDeviceStateCallBack;
import com.tongtailian.www.stir.utils.BleManageUtil;
import com.tongtailian.www.stir.utils.LogUtil;
import com.tongtailian.www.stir.utils.ToastUtils;
import com.tongtailian.www.stir.utils.gson.GsonUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuml on 2020/9/5 17:26
 */
public class SelectParameActivity extends BaseActivity {
    private RecyclerView rvSampleNumber;
    private Button btCleanWater;
    private Button btCleanSolvent;
    private Button btCleanUltrasonic;
    private RecyclerView rvBatch;
    private RecyclerView rvSelectParame;


    private List<NumberBean> demoLocationList = new ArrayList<>();//研磨罐数量
    private List<ConfigBean> runTypelist = new ArrayList<>();//研磨模式
    private SelectGroupAdapter selectGroupAdapter;
    private ConfigAdapter configAdapter;

    private int oldSelectPosition = 0;
    String nameArray[] = {"根茎类", "叶菜类", "花果菜类", "干果类", "水果类", "谷物类", "鱼肉类", "其他类"};
    String valueArray[] = {"样品重量≤500克，如：萝卜、胡萝卜、豆薯、甘薯、主要有莴笋、茎用芥菜、球茎甘蓝、竹笋、土豆、莲藕、洋葱、大蒜等。",
            "样品重量≤500克，如：白菜、菠菜、苋菜、莴苣、韭菜、芹菜等",
            "样品重量≤500克，如：金针菜、花椰菜、紫菜薹、南瓜、黄瓜、冬瓜、丝瓜、番茄、辣椒、茄子、豆角等",
            "样品重量≤500克，如：杏仁、腰果、榛子、核桃、板栗、白果、花生、葵花子、南瓜子、板栗、杏仁等（坚果类需去壳）",
            "样品重量≤500克，如：草莓、蓝莓、覆盆子、橘子、柠檬、柚子、葡萄、桃、枣、龙眼、荔枝、苹果、梨、柿子等",
            "样品重量≤500克，如：薏米、高梁、大麦、糙米、红小豆、小米、黑豆、黄豆等",
            "样品重量≤500克，如：活鱼、虾、海鲜、牛肉、羊肉、猪肉。含内脏含熟食",
            "样品重量≤500克，难处理的样品：粉丝、西兰花、蒜苗等"};
    private String locationList;

    private boolean isDef = false;

    private TextView tv_group;
    private MyBleDeviceStateCallBack myBleDeviceStateCallBack;

    @Override
    public int setLayoutId() {
        return R.layout.activity_select_parame;
    }

    @Override
    public void initVariables() {
        setTitle("选择参数");
        setTvRight("确认选择");
        llRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        llLeft.setVisibility(View.GONE);

        isDef = getIntent().getBooleanExtra("isDef",false);

        locationList = spManager.getLocationList();
        oldSelectPosition = spManager.getGroup();
        LogUtil.d("locationList = " + locationList);
        if (TextUtils.isEmpty(locationList)) {
            for (int i = 1; i <= 4; i++) {
                NumberBean bean = new NumberBean();
                bean.setName(String.valueOf(i) + "组");
                bean.setGroup_name("根茎类");
                bean.setGroup(0);
                bean.setSelect(true);
                demoLocationList.add(bean);
            }
            spManager.saveLocationList(GsonUtil.gsonString(demoLocationList));
        } else {
            demoLocationList = GsonUtil.jsonToList(locationList, NumberBean.class);
//            LogUtil.d(GsonUtil.gsonString(list1));
        }
//        NumberBean bean1 = new NumberBean();
//        bean1.setName("全选");
//        bean1.setSelect(false);
//        list1.add(bean1);
    }


    private void updateList(){
        String runType = spManager.getRunType();
        LogUtil.d("获取的runType = " + locationList);
        LogUtil.d("nameArray.length = "+nameArray.length);
        if (TextUtils.isEmpty(runType)) {
            for (int i = 1; i <= 63; i++) {
                ConfigBean bean = new ConfigBean();

                if (i <= nameArray.length) {
                    bean.setLook("查看");
                    bean.setEdit(false);
                    bean.setName(nameArray[i - 1]);
                    bean.setValue(valueArray[i - 1]);
                } else {
                    bean.setLook("编辑");
                    bean.setEdit(true);
                    bean.setName("自定义" + String.valueOf(i - 1));
                }
                bean.setSelect(false);
                runTypelist.add(bean);
            }
            LogUtil.d("保存的 = " + GsonUtil.gsonString(runTypelist));
            spManager.saveRunType(GsonUtil.gsonString(runTypelist));
        } else {
            runTypelist = GsonUtil.jsonToList(runType, ConfigBean.class);
            LogUtil.d("获取的的 = " + GsonUtil.gsonString(runTypelist));
        }
        configAdapter.setNewData(runTypelist);
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateList();
    }

    @Override
    public void initViews(Bundle savedInstanceState) {

        rvSampleNumber = findViewById(R.id.rv_sample_number);
        btCleanWater = findViewById(R.id.bt_clean_water);
        btCleanSolvent = findViewById(R.id.bt_clean_solvent);
        btCleanUltrasonic = findViewById(R.id.bt_clean_ultrasonic);
        rvBatch = findViewById(R.id.rv_batch);
        rvSelectParame = findViewById(R.id.rv_select_parame);
        tv_group = findViewById(R.id.tv_group);

        if(isDef){
            rvSampleNumber.setVisibility(View.VISIBLE);
            tv_group.setVisibility(View.VISIBLE);
        }
        else{
            rvSampleNumber.setVisibility(View.GONE);
            tv_group.setVisibility(View.GONE);
        }

        //研磨罐数量
        selectGroupAdapter = new SelectGroupAdapter(R.layout.adapter_item_number, demoLocationList);
        //多列创建布局管理
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvSampleNumber.setLayoutManager(gridLayoutManager);
        rvSampleNumber.setAdapter(selectGroupAdapter);

        selectGroupAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LogUtil.d("研磨罐点击" + position);

                int selCount = 0;
                for (int i = 0; i < demoLocationList.size(); i++) {
                    if (demoLocationList.get(i).isSelect()) {
                        selCount++;
                    }
                }
                if(selCount == 0 && position == 0){
                    changeGroupType(position);
                }else if(selCount > 0 &&(position+1 == selCount || position+1 == (selCount+1)) ){
                    changeGroupType(position);
                }else{
                    ToastUtils.showCenter("请按顺序进行选择");
                }

            }
        });


        configAdapter = new ConfigAdapter(R.layout.adapter_item_config, runTypelist,isDef);
        rvSelectParame.setLayoutManager(new LinearLayoutManager(this));
        rvSelectParame.setAdapter(configAdapter);


        configAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                LogUtil.d("研磨模式点击" + position);
                switch (view.getId()) {
                    case R.id.bt_item_name:
                        if(!isDef)return;
                        runTypelist.get(oldSelectPosition).setSelect(false);
                        runTypelist.get(position).setSelect(true);
                        oldSelectPosition = position;
                        spManager.saveRunType(GsonUtil.gsonString(runTypelist));
                        spManager.saveSelectGroup(oldSelectPosition);
                        configAdapter.setNewData(runTypelist);
                        break;
                    case R.id.bt_item_look:

                        Intent intent = new Intent();
                        intent.putExtra("bean", runTypelist.get(position));
                        intent.putExtra("position",(position));
                        startActivity(intent, EditAndLookConfigActivity.class);
                        break;
                }
            }
        });

    }

    public void changeGroupType(int position){

        if(doingIndex == position + 1){
            ToastUtils.showCenter("当前罐体研磨中");
            return;
        }

        if (demoLocationList.get(position).isSelect()) {
            demoLocationList.get(position).setSelect(false);
        } else {
            demoLocationList.get(position).setSelect(true);
        }
        selectGroupAdapter.setNewData(demoLocationList);
        spManager.saveLocationList(GsonUtil.gsonString(demoLocationList));
    }

    @Override
    public void doBusiness() {
        spManager.saveCurModle(1);
        bleManageUtil = BleManageUtil.getInstance();//初始化蓝牙
    }

    private int flow;
    private int dataDev;
    private int doingIndex = -1;
    private BleManageUtil bleManageUtil;

    private CountDownTimer timer;//定时器查询工作状态
    //这是定时器
    public void runDymCodeTimer() {
        LogUtil.d("runTimer启动定时器开始");
        if (timer != null) {
            LogUtil.d("启动定时器 失败 timer != null");
            return;
        }
        LogUtil.d("启动定时器 number = ");
        if (bleManageUtil != null && BleManageUtil.getInstance().isConnect) {
            LogUtil.d("启动定时器 number = ");
            timer = new CountDownTimer(Long.MAX_VALUE, 2000) {
                @Override
                public void onFinish() {
                    cancel();
                }

                @Override
                public void onTick(long millisUntilFinished) {
                    if (bleManageUtil != null && bleManageUtil.isPlaying && BleManageUtil.getInstance().isConnect) {
                        getDeviceState();
                        //getDevicemodle();
                    }
                }
            }.start();
        }
    }

    /**
     * 获取设备状态
     */
    private void getDeviceState() {
        /**
         * Flow
         * 0x01 位置初始化
         * 0x02 定位流程
         * 0x03 超声波清洗
         * 0x04 热风烘干
         * 0x05 清水清洗
         * 0x06 研磨工作
         *
         * 正常流程结束，Flow = 0x06， Step = 0xA0.
         * 指令结束流程，Flow = 0x10， Step = 0xA0.
         * 异常结束流程，Flow = 0x10， Step = 0xA0.
         */
        if (myBleDeviceStateCallBack == null) {
            myBleDeviceStateCallBack = new MyBleDeviceStateCallBack() {

                @Override
                public void onDevicesState(DeviceStateFram deviceStateFram) {

                    //{name=1, Flow=6, Step=0, DataDev=0}
                    flow = deviceStateFram.getFlow();
                    int step = deviceStateFram.getStep();
                    LogUtil.d(" 当前设备状态 = " + GsonUtil.gsonString(deviceStateFram));


                    switch (flow) {

                        case 6:
                            LogUtil.d("研磨中 flow = 6  dataDev= " + dataDev + " getStep = " + deviceStateFram.getStep());
                            //0x06工 作流程 正在研磨
                            doingIndex = deviceStateFram.getDataDev();;
                            break;
                    }

                    if (step == 160) {
                        cancle();
                        doingIndex = -1;
                        /*for (int i = 0; i < demoLocationList.size(); i++) {
                            demoLocationList.get(i).setSelect(false);
                        }
                        selectGroupAdapter.setNewData(demoLocationList);
                        spManager.saveLocationList(GsonUtil.gsonString(demoLocationList));
                        ToastUtils.showCenter("停止工作");*/

                    }
                }

                @Override
                public void onFail() {

                }
            };
        }

        BleManageUtil.getInstance().readDevicesState(myBleDeviceStateCallBack);


    }

    public void cancle() {
        if (timer != null) {
//            LogUtil.d("取消定时器");
            timer.cancel();
            timer = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancle();
    }
}